using System.Net;
using DotNetCore.CAP;
using FluentValidation;
using IdGen;
using Zhaoxi.MSACommerce.OrderService.Core.Entities;
using Zhaoxi.MSACommerce.OrderService.Infrastructure.Data.Configuration;
using Zhaoxi.MSACommerce.OrderService.UseCases.Service;
using Zhaoxi.MSACommerce.SharedEvent.Orders;
using ZhaoXi.MSACommerce.SharedKenel.Messaging;
using ZhaoXi.MSACommerce.SharedKenel.Result;
using ZhaoXi.MSACommerce.UserCases.Common.Interfaces;

namespace Zhaoxi.MSACommerce.OrderService.UseCases.Commands;

public record CreateOrderCommand(OrderForCreateDto Order) : ICommand<Result<long>>;

public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
    public CreateOrderCommandValidator()
    {
        RuleFor(query  =>query.Order.Carts )
            .Must(x=>x.Count > 0);
    }
}

public class CreateOrderCommandHandler(
    OrderDbContext dbContext,
     IProductClient productClient,
    IUser user,
    ICapPublisher capPublisher,
    IIdGenerator<long> idGen) : ICommandHandler<CreateOrderCommand, Result<long>>
{
    public async Task<Result<long>> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
    {
        var order = new Order(idGen.CreateId())
        {
            UserId = (long)user.Id,
            Receiver = "张三",
            ReceiverAddress = "朝夕",
            PaymentType = request.Order.PaymenType
        };

        var skuNum = request.Order.Carts.ToDictionary(m => m.SkuId, m => m.Quantity);

        //获取商品信息  调用商品服务
        var skuResponse = await productClient.GetSkuListAsync(skuNum.Keys.ToArray());

        if (skuResponse.StatusCode == HttpStatusCode.NotFound) return Result.NotFound("商品信息不存在");

        if (!skuResponse.IsSuccessStatusCode) return Result.Failure("商品信息获取失败");

        //var skus = skuResponse.Content;

       // foreach (var sku in skus)
       // {
            order.AddOrderDetail(new OrderDetail
            {
                Name = "iPhone 14 Pro 128GB 深空黑色",
                Quantity = 2,
                Price = 799900,
                Spec = "这是规格",
                Image = "这是图片",
                SkuId = 20250808,
            });
        //}

        // 模拟打折金额
        var PostFee = 1;
        //计算实付金额
        order.ActualPay = order.TotalPay - PostFee;

        //分布式事务
        await using (var trans =
                     await dbContext.Database.BeginTransactionAsync(capPublisher, cancellationToken: cancellationToken))
        {
            dbContext.Orders.Add(order);
            await dbContext.SaveChangesAsync(cancellationToken);

            var orderCreateEvent = new OrderCreatedEvent()
            {
                OrderId = order.Id,
                Skus = order.OrderDetails.Select(x => new OrderSku(x.SkuId, x.Quantity)).ToList(),
            };
            await capPublisher.PublishAsync(nameof(OrderCreatedEvent), orderCreateEvent,nameof(OrderCreatedEventResult), cancellationToken);
            await trans.CommitAsync(cancellationToken);
        }

        return Result.Success(order.Id);
    }
}